package com.february.todo;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.hardware.Camera;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

public class TakePhotoActivity extends AppCompatActivity {
    private SurfaceHolder surfaceHolder;
    private Camera camera;

    Intent intent;
    private final SurfaceHolder.Callback surfaceHolderCallback=new SurfaceHolder.Callback(){
        @Override
        public void surfaceCreated(@NonNull SurfaceHolder holder) {
            surfaceHolder = holder;
            if (camera == null) {
                try {
                    camera=Camera.open(0);
                } catch (Exception e) {
                    return;
                }
                //获取Camera参数
                Camera.Parameters params=camera.getParameters();
                if (params.getSupportedFocusModes().contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
                    // 自动对焦
                    params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
                }

                params.setPreviewFormat(ImageFormat.NV21); // 设置预览图片格式
                params.setPictureFormat(ImageFormat.JPEG); // 设置拍照图片格式
                camera.setParameters(params);

                try {
                    camera.setPreviewDisplay(holder);
                    //旋转90度
                    camera.setDisplayOrientation(90);
                    camera.startPreview();
                } catch (Exception ex) {
                    ex.printStackTrace();
                    camera.release();
                    camera=null;
                }
            }
        }

        @Override
        public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {

        }

        @Override
        public void surfaceDestroyed(@NonNull SurfaceHolder holder) {
            if (camera != null) {
                camera.setPreviewCallback(null);
                camera.stopPreview();
                camera.release();
                camera=null;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_take_photo);

        Button btn_return = findViewById(R.id.btn_return);
        Button btn_shoot=findViewById(R.id.btn_shoot);

        SurfaceView surfaceView = findViewById(R.id.surfaceView);
        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(surfaceHolderCallback);

        intent=new Intent();

        btn_return.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        @SuppressLint("StaticFieldLeak")
        class SavePictureTask extends AsyncTask<byte[], String, String> {
            @Override
            protected String doInBackground(byte[]... params) {
                SimpleDateFormat time =new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒", Locale.getDefault());
                String filename=time.format(new Date().getTime());
                intent.putExtra("filename",filename);
                File picture = new File("/storage/emulated/0/Pictures/"+filename+".jpg");
                try {
                    FileOutputStream fos = new FileOutputStream(picture.getPath());
                    fos.write(params[0]);
                    fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
        }

        btn_shoot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                camera.takePicture(null, null, new Camera.PictureCallback() {
                    @Override
                    public void onPictureTaken(byte[] data, Camera camera) {
                        new SavePictureTask().execute(data);
                        Bitmap bitmap= BitmapFactory.decodeByteArray(data,0, data.length);

                        LayoutInflater inflater = (LayoutInflater) TakePhotoActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                        View layout = inflater.inflate(R.layout.preview_dialog, null);

                        ImageView preview=layout.findViewById(R.id.img_preview);
                        preview.setImageBitmap(bitmap);
                        preview.setRotation(90);

                        AlertDialog.Builder builder=new AlertDialog.Builder(TakePhotoActivity.this);
                        builder.setTitle("图像预览");
                        builder.setView(layout);
                        builder.show();

                        builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {
                                finish();
                            }
                        });

                        TimerTask task=new TimerTask() {
                            @Override
                            public void run() {
                                setResult(RESULT_OK,intent);
                                finish();
                            }
                        };
                        Timer timer=new Timer();
                        timer.schedule(task,3000);
                    }
                });
            }
        });
    }
}